<?php
/**
 * Created by PhpStorm.
 * User: iyahe@qq.com (天明)
 * Date: 2017/12/13
 * Time: 10:08
 */
namespace app\api\controller;
use app\action;
use app\api\model\KefuModel;
use app\api\model\MessageModel;
use app\api\model\UserModel;
use think\Cache;

class Kefu extends action
{
    public $postData;
    public $SessionFrom;
    public $sendOpenid;
    public function __construct()
    {
        parent::__construct();
    }
    public function index(){}
    public function start(){
        $pex = 'kefu_';
        $form = 'fm_';
        if($this->comeHere()) {
            $this->postData = $this->getData();
            self::logger($this->postData,'微信推流');
            if(isset($this->postData['SessionFrom'])) {
                $this->SessionFrom = json_decode($this->postData['SessionFrom'],true);
                self::logger($this->SessionFrom,'用户初始化的SessionFrom');
                //获取消息接收人的openid,然后保存
                $sendInfo = UserModel::make()->getUserInfo($this->SessionFrom['uid'],'user_openid');
                Cache::set($pex.$this->postData['FromUserName'],$sendInfo['user_openid']);
                self::logger($sendInfo,'获取消息接收人的openid');
                //获取发送人的人(自己的)openid;保存在接收人人的接收对象里
                //保存在接收人的数组里
                Cache::set($pex.$sendInfo['user_openid'],$this->postData['FromUserName']);
                //保存sessionForm
                Cache::set($form.$this->postData['FromUserName'],$this->SessionFrom);
                Cache::set($form.$sendInfo['user_openid'],$this->SessionFrom);
                self::logger($this->SessionFrom,'SessionFrom');
            }else{
                $this->SessionFrom = cache($form.$this->postData['FromUserName']);
                $this->sendOpenid = cache($pex.$this->postData['FromUserName']);
                self::logger($this->SessionFrom,'缓存的SessionFrom');
                self::logger($this->sendOpenid,'缓存的sendOpenid');
                if(!$this->SessionFrom){
                    $sendStrData = $this->textTemplate('系统','请在小程序内和您需要对话的玩伴重新发起会话哦!');
                    return $this->sendKefuMessage($this->postData['FromUserName'],$sendStrData,'text');
                }
            }
            return MessageModel::make()->KefuCenter($this->postData,$this->SessionFrom,$this->sendOpenid);
        }
    }
    public function comeHere(){
        $signature = input('signature');
        $timestamp = input('timestamp');
        $nonce = input('nonce');
        $token = 'cec843d576d3055004fcb5a450445675';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    public function getData(){
        $ysData = file_get_contents("php://input");
        self::logger($ysData,'流数据');
        self::logger($_REQUEST,'GET数据');
        return json_decode($ysData,true);
    }
    /** 回复客服消息
     * @param        $openid 接收人openid
     * @param        $content 发送的内容
     * @param string $type 消息类型
     * @return bool|mixed
     */
    public function sendKefuMessage($openid,$content,$type='text'){
        if(!is_array($content)) $content = ['content'=>$content];
        $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->accessToken();
        $postData = KefuModel::make()->makeKefuData($openid,$type,$content);
        setlogs($postData,'准备发送的客服消息信息');
        $result = https_request($postUrl,json_encode($postData,JSON_UNESCAPED_UNICODE));
        $msgCode = json_decode($result,true);
        setlogs($msgCode,'客服消息信息返回');
        if($msgCode['errcode'] == 0) {
            return true;
        }else{
            return $msgCode;
        }
    }
    /** 发送模板消息
     * @param $data data数组
     * @return bool|mixed 返回结果
     */
    public function sendTemplateMessage($data){
        $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$this->accessToken();
        $sendData = [];
        $sendData['touser'] = $data['openid'];
        $sendData['template_id'] = $data['template_id'];
        $sendData['page'] = $data['url'];
        $sendData['form_id'] = $data['formId'];
        $sendData['data'] = $data['keyword'];
        $sendData['color'] = '';
        $sendData['emphasis_keyword'] = '';
        $msgData = https_request($postUrl,json_encode($sendData,JSON_UNESCAPED_UNICODE));
        $msgCode = json_decode($msgData,true);
        if($msgCode['errcode'] == 0) {
            return true;
        }else{
            return $msgCode;
        }
    }
    private function getAccessToken(){
        $wx_appid = config('wx_appid');
        $wx_secret = config('wx_secret');
        $tokenUrl =  'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$wx_appid.'&secret='.$wx_secret;
        $result = https_request($tokenUrl);
        $acToken = json_decode($result,true);
        if(isset($acToken['errcode'])) {
            self::logger($acToken,'token获取失败');
        }else{
            Cache::set(
                'wx_accessToken',$acToken['access_token'],
                intval($acToken['expires_in'])-200
            );
            self::logger($acToken,'token获取成功');
            return $acToken['access_token'];
        }
    }
    public function accessToken(){
        if($token = cache('wx_accessToken')) {
            self::logger($token,'从缓存获取token成功');
            return $token;
        }else{
            return $this->getAccessToken();
        }
    }
    public function textTemplate($nickname,$content){
        $str = <<<SET
----------------------------
---收到{$nickname}发来的消息---
----------------------------
{$content}
SET;
        self::logger($str,'回话消息模板');
        return $str;
    }
    private function replyRobot(){
        $data = [];
    }
    public function test(){

    }
}